# -*- coding: utf-8 -*-
import requests
import datetime
import time
import pymongo
import json
import hashlib
from mongo_config import *

mongo_client = pymongo.MongoClient(MONGO_URL, 27017)
db = mongo_client[MONGO_DB]
collection_bi = db['jinse_lives']

def select_info():
    for item in collection_bi.find():
        if item['rank']== '1' and item['flag'] == 0:
            judge(item['issue_time'], item['title'], item['content'])
            collection_bi.update({'flag':0,'rank':'1'}, {'$set':{'flag':1}})

# 提交资讯内容
def judge(issue_time, title, content):
    header = {'content-type': 'application/json;charset=utf8'}
    url = 'http://coincoin.laifusi.com/coin/api/insert_news'
    issue_time = issue_time
    title = title
    content = content
    sign = '2HClEb8nSwZR3s4q33xmfH85KpE5DZn0qcqvtEryU4nTiwgGvj8ufF0iV1wKVJKmCkOjKsTupV' + str(int(time.time()))
    sha256 = hashlib.sha256()
    sha256.update(sign.encode('utf-8'))
    sign = sha256.hexdigest()
    content = {
        'time': int(time.time()),
        'sign': sign,
        'data': {'all': [{
            'issue_time': str(issue_time).replace('\n', ''),
            'title': str(title).replace('\n', ''),
            'content': str(content).replace('\n', '')}]},
        'connection': ['all'],
    }
    print(content)
    base_post = requests.post(url, data=json.dumps(content, ensure_ascii=False).encode('utf-8'), headers=header)

def main():
    select_info()

if __name__ == '__main__':
    flag = 0
    max_time = 0
    # 获取当前时间
    now = datetime.datetime.now()
    # 启动时间
    # 启动时间为当前时间 加2秒
    sched_timer = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute,
                                    now.second) + datetime.timedelta(seconds=2)
    while (True):
        # 当前时间
        now = datetime.datetime.now()
        # 毫秒级的时间相等成功率很低 而且存在启动时间秒级与当前时间毫秒级比较的问题
        # 后来换成了以下方式，允许1秒之差
        if sched_timer < now < sched_timer + datetime.timedelta(seconds=1):
            time.sleep(1)
            print(now)
            # 运行程序
            main()
            # 将标签设为 1
            flag = 1
        else:
            # 标签控制 表示主程序已运行，才修改定时任务时间
            if flag == 1:
                # 修改定时任务时间 时间间隔为1分钟
                sched_timer = sched_timer + datetime.timedelta(minutes=5)
                flag = 0